/**
 * 
 */
package com.apanal.qlife.property.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.apanal.qlife.common.constants.Constants;
import com.apanal.qlife.common.page.Page;
import com.apanal.qlife.common.page.PageReturn;
import com.apanal.qlife.common.util.IdWorkerFactory;
import com.apanal.qlife.org.dao.OrganizationMapper;
import com.apanal.qlife.org.model.Organization;
import com.apanal.qlife.property.dao.CommunityMapper;
import com.apanal.qlife.property.model.Community;
import com.apanal.qlife.property.service.CommunityService;
import com.apanal.qlife.sys.dao.AreaMapper;
import com.apanal.qlife.sys.dao.DictionaryMapper;
import com.apanal.qlife.sys.model.Area;
import com.apanal.qlife.sys.model.Dictionary;
import com.apanal.qlife.sys.model.User;

/**
 * @author Admin
 *
 */
@Service
public class CommunityServiceImpl implements CommunityService {

	@Autowired
	private CommunityMapper communityMapper;
	
	@Autowired
	private AreaMapper areaMapper;
	
	@Autowired
	private OrganizationMapper organizationMapper;
	
	@Autowired
	private DictionaryMapper dictionaryMapper;
	
	public PageReturn<Community> findCommunityList(Community community,Page page)
	{
		int count = communityMapper.findCommunityListCount(community);
		List<Community> list = communityMapper.findCommunityList(community,page);
		return new PageReturn<Community>(list,count,page,community);
	}
	
	
	public Community findCommunity(Community community)
	{
		return communityMapper.findCommunity(community.getComId());
	}
	
	public int saveCommunity(Community community)
	{
		community.setComId(IdWorkerFactory.nextId());
		return communityMapper.saveCommunity(community);
	}
	
	public int updateCommunity(Community community)
	{
		return communityMapper.updateByPrimaryKey(community);
	}
	
	public int updateCommunityNormal(Community community)
	{
		return communityMapper.updateByPrimaryKeySelective(community);
	}


	@Override
	public PageReturn<Community> selectRelationForPage(Community community,
			Page page) {
		int count = communityMapper.selectRelationForPageCount(community, page);
	    List<Community> list = communityMapper.selectRelationForPage(community, page);
		return new PageReturn<Community>(list, count, page, community);
	}


	@Override
	public List<Community> selectByIds(String ids) {
		if(ids == null || "".equals(ids)){
			return null;
		}else{
			Community param = new Community();
			param.setCommIds(ids);
			return communityMapper.select(param);
		}
	}
	
	public String importExcelCommunity(InputStream inputStream,User user)
	{
		HSSFWorkbook hssfWorkbook = null;
		StringBuffer msg = new StringBuffer("");
		List<Community> list = new ArrayList<Community>();
		String orgName = "";
		try {
			hssfWorkbook = new HSSFWorkbook(inputStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
		 
        // 循环工作表Sheet
        for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
            HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
            if (hssfSheet == null || hssfSheet.getLastRowNum() < 1) {
				msg.append("sheet" + (numSheet + 1) + "表格数据不能为空!<br>");
				// return msg.toString();
			}
            if (hssfSheet == null) {
                continue;
            }
 
            // 循环行Row
            for (int rowNum = 3; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
                HSSFRow hssfRow = hssfSheet.getRow(rowNum);
                Community community = new Community();
                if (hssfRow == null) {
                    continue;
                }
 
                // 循环列Cell
                Area area = new Area();
                for (int cellNum = 0; cellNum <= hssfRow.getLastCellNum(); cellNum++) {
                    HSSFCell hssfCell = hssfRow.getCell(cellNum);
                    if (hssfCell == null) {
                        continue;
                    }
                    switch(cellNum){
                    	case 0:
                    		isEmpty(msg, getValue(hssfCell), numSheet + 1, rowNum + 1, cellNum + 1);
                    		community.setComId(IdWorkerFactory.nextId());
                    		break;
                    	case 1:
                    		isEmpty(msg, getValue(hssfCell), numSheet + 1, rowNum + 1, cellNum + 1);
                    		community.setComName(getValue(hssfCell));
                    		break;
                    	case 2:
                    		isEmpty(msg, getValue(hssfCell), numSheet + 1, rowNum + 1, cellNum + 1);
                    		if(getValue(hssfCell).equals(Constants.COM_YES)){
                    			community.setComIsCheck(1);
                    			orgName = getValue(hssfCell);
                    		}else {
                    			community.setComIsCheck(0);
                    		}
                    		break;
                    	case 3:
                    		isEmpty(msg, getValue(hssfCell), numSheet + 1, rowNum + 1, cellNum + 1);
                    		if(orgName.equals(Constants.COM_YES)){
                    			Organization organization = new Organization();
                    			organization.setOrgName(getValue(hssfCell));
                    			organization.setOrgType(3);
                    			List<Organization> orgList = organizationMapper.findOrgList(organization);
                    			if(orgList != null && orgList.size() > 0){
	                    			community.setOrgName(orgList.get(0).getOrgName());
	                    			community.setOrgId(orgList.get(0).getOrgId());
                    			}else{
                    				msg.append("sheet" + (numSheet + 1) + "第" + (rowNum + 1) + "行第" + (cellNum + 1) + "列物业信息查询为空!<br>");
                    			}
                    		}else{
                    			community.setOrgName(getValue(hssfCell));
                    		}
                    		break;
                    	case 4:
                    		isEmpty(msg, getValue(hssfCell), numSheet + 1, rowNum + 1, cellNum + 1);
                    		community.setComContactName(getValue(hssfCell));
                    		break;
                    	case 5:
                    		isEmpty(msg, getValue(hssfCell), numSheet + 1, rowNum + 1, cellNum + 1);
                    		community.setComContactMobile(getValue(hssfCell));
                    		break;
                    	case 6:
                    		isEmpty(msg, getValue(hssfCell), numSheet + 1, rowNum + 1, cellNum + 1);
                    		area.setAreaName(getValue(hssfCell));
                    		area.setAreType(1);
                    		List<Area> list1 = areaMapper.findAreaList(area);
                    		if(list1 != null && list1.size() > 0 ){
                    			community.setProvinceId(list1.get(0).getAreId());
                    		}else{
                    			msg.append("sheet" + (numSheet + 1) + "第" + (rowNum + 1) + "行第" + (cellNum + 1) + "列所在省份错误!<br>");
                    		}
                    		break;
                    	case 7:
                    		isEmpty(msg, getValue(hssfCell), numSheet + 1, rowNum + 1, cellNum + 1);
                    		area.setAreaName(getValue(hssfCell));
                    		area.setAreType(2);
                    		List<Area> list2 = areaMapper.findAreaList(area);
                    		if(list2 != null && list2.size() > 0 ){
                    			community.setCityId(list2.get(0).getAreId());
                    		}else{
                    			msg.append("sheet" + (numSheet + 1) + "第" + (rowNum + 1) + "行第" + (cellNum + 1) + "列所在城市错误!<br>");
                    		}
                    		break;
                    	case 8:
                    		isEmpty(msg, getValue(hssfCell), numSheet + 1, rowNum + 1, cellNum + 1);
                    		area.setAreaName(getValue(hssfCell));
                    		area.setAreType(3);
                    		List<Area> list3 = areaMapper.findAreaList(area);
                    		if(list3 != null && list3.size() > 0 ){
                    			community.setAreaId(list3.get(0).getAreId());
                    		}else{
                    			msg.append("sheet" + (numSheet + 1) + "第" + (rowNum + 1) + "行第" + (cellNum + 1) + "列所在区/县错误!<br>");
                    		}
                    		break;
                    	case 9:
                    		isEmpty(msg, getValue(hssfCell), numSheet + 1, rowNum + 1, cellNum + 1);
                    		community.setComAddress(getValue(hssfCell));
                    		break;
                    	case 10:
                    		isEmpty(msg, getValue(hssfCell), numSheet + 1, rowNum + 1, cellNum + 1);
                    		community.setComContent(getValue(hssfCell));
                    		break;
                    	case 11:
                    		isEmpty(msg, getValue(hssfCell), numSheet + 1, rowNum + 1, cellNum + 1);
                    		community.setComBuildingDate(getValue(hssfCell));
                    		break;
                    	case 12:
                    		isEmpty(msg, getValue(hssfCell), numSheet + 1, rowNum + 1, cellNum + 1);
                    		Dictionary dictionary = new Dictionary();
                    		dictionary.setType("BUILDING_TYPE");
                    		dictionary.setContent(getValue(hssfCell));
                    		List<Dictionary> dl = dictionaryMapper.selectAllByType(dictionary);
                    		if(dl != null && dl.size() > 0){
                    			community.setComBuildingType(dl.get(0).getCode());
                    		}else{
                    			msg.append("sheet" + (numSheet + 1) + "第" + (rowNum + 1) + "行第" + (cellNum + 1) + "列建筑类型错误!<br>");
                    		}
                    		break;
                    	case 13:
                    		isEmpty(msg, getValue(hssfCell), numSheet + 1, rowNum + 1, cellNum + 1);
                    		community.setComFloorArea(Float.parseFloat(getValue(hssfCell)));
                    		break;
                    	case 14:
                    		isEmpty(msg, getValue(hssfCell), numSheet + 1, rowNum + 1, cellNum + 1);
                    		community.setComHousingNumber(Integer.valueOf(getValue(hssfCell)));
                    		break;
                    	case 15:
                    		isEmpty(msg, getValue(hssfCell), numSheet + 1, rowNum + 1, cellNum + 1);
                    		community.setStatus(Integer.valueOf(getValue(hssfCell)));
                    		break;
                    }
                }
                community.setNormal(1);
                community.setInsertBy(user.getComId());
                community.setLastUpdateBy(user.getComId());
                list.add(community);
            }
        }
        if (msg.length() == 0) {
//	        for (Community cm : list) {
//	        	communityMapper.insert(cm);
//	        }
        	communityMapper.saveCommunityList(list);
        }
		return msg.toString();
	}
	
    private String getValue(HSSFCell hssfCell) {
    	String result = "";
        if (hssfCell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
            return String.valueOf(hssfCell.getBooleanCellValue());
        } else if (hssfCell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
        	if (HSSFDateUtil.isCellDateFormatted(hssfCell)) {// 处理日期格式、时间格式  
                SimpleDateFormat sdf = null;  
                if (hssfCell.getCellStyle().getDataFormat() == HSSFDataFormat  
                        .getBuiltinFormat("h:mm")) {  
                    sdf = new SimpleDateFormat("HH:mm");  
                } else {// 日期  
                    sdf = new SimpleDateFormat("yyyy-MM-dd");  
                }  
                Date date = hssfCell.getDateCellValue();  
                result = sdf.format(date);  
            } else {
            	double value = hssfCell.getNumericCellValue();  
                CellStyle style = hssfCell.getCellStyle();  
                DecimalFormat format = new DecimalFormat();  
                String temp = style.getDataFormatString();  
                // 单元格设置成常规  
                if (temp.equals("General")) {  
                    format.applyPattern("#");  
                }  
                result = format.format(value);  
            }
            return result;
        } else {
            return String.valueOf(hssfCell.getStringCellValue());
        }
    }
    
    private boolean isEmpty(StringBuffer msg, String str, int sheet, int row,
			int cell) {
		if (str == null || "".equals(str.trim())) {
			msg.append("sheet" + sheet + "第" + row + "行第" + cell + "列不能为空!<br>");
			return true;
		} else {
			return false;
		}
	}
}
